import numpy as np
import argparse
import cv2

ap = argparse.ArgumentParser()
ap.add_argument("-img1", "--image1", type=str, required=True,
                help="the first image path to input")
ap.add_argument("-img2", "--image2",type=str, required=True,
                help="the second image path to input")
args = vars(ap.parse_args())

img1 = cv2.imread(args["image1"],0)
img2 = cv2.imread(args["image2"],0)

#img1 = cv2.reize(img1,(0,0),0.3,0.3)

sift = cv2.SIFT_create()

(kp1, des1) = sift.detectAndCompute(img1, None)
(kp2, des2) = sift.detectAndCompute(img2, None)

# 1:1匹配
bf = cv2.BFMatcher(crossCheck=True)#蛮力匹配互相检测匹配
matches = bf.match(des1,des2)
matches = sorted(matches,key=lambda x: x.distance)
print("len(matches):"+str(len(matches)))

good_matches = []
for m in matches:
    if len(m) == 2 and m[0].distance < 0.4 * m[1].distance: #d1 < 0.4*d2
        good_matches.append((m[0].queryIdx,m[0].trainIdx))
print(good_matches)

#7.将可靠的匹配转换数据类型
kps1 = np.float32([kp.pt for kp in kp1])   #求出所有关键点的x,y坐标
kps2 = np.float32([kp.pt for kp in kp2])

kps1 = np.float32([kps1[a[0]] for a in good_matches])   #求出可靠匹配的x,y坐标
kps2 = np.float32([kps2[a[1]] for a in good_matches])

#8.求解转换矩阵
(M, mask) = cv2.findHomography(kps2, kps1, cv2.RANSAC,4.0)	#默认3.0，错误阈值
print(M)
diff_x = M[0][2]/M[2][2]
rate = diff_x/img1.shape[1]
print(rate)